<template>
  <div class="loginbox">
    <!-- 左侧图片 -->
    <div class="left"></div>
    <!-- 右侧登录表单 -->
    <div class="right">
      <form v-on:submit.prevent class="loginform">
        <!-- 标题 -->
        <div class="loginformHeader">
          <h2>欢迎登录！</h2>
          <span>智慧植物培养皿管理系统</span>
        </div>
        <!-- 输入框 -->
        <div class="inputbox">
          <div class="userlogin">
            <span>用户名</span>
            <div class="userbox">
              <el-input
                aria-required="true"
                v-model="username"
                placeholder="用户名"
                ><template #prefix>
                  <el-icon class="el-input__icon"><User /></el-icon>
                </template>
              </el-input>
            </div>
            <span>密码 </span>
            <div class="passwordbox">
              <el-input
                v-model="password"
                placeholder="密码"
                :type="addPassFlag ? 'text' : 'password'"
                onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"
              >
                <template #prefix>
                  <el-icon class="el-input__icon"><Lock /></el-icon>
                </template>
                <template #suffix>
                  <span @click="addPassFlag = !addPassFlag">
                    <el-icon v-if="addPassFlag"><View /></el-icon>
                    <el-icon v-else><Hide /></el-icon>
                  </span>
                </template>
              </el-input>
            </div>
          </div>
          <!-- 验证码 -->
          <div class="codebox">
            <el-input
              v-model="code"
              placeholder="验证码"
              onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"
              ><template #prefix> </template>
            </el-input>
            <Identify
              :identifyCode="identifyCode"
              :contentWidth="130"
              :contentHeight="45"
              @click="changeCode"
            />
          </div>
          <!-- 记住密码 -->
          <div class="otherbox">
            <div class="remember">
              <input type="checkbox" @click="setpassword" id="check" />
              <span>记住密码</span>
            </div>
            <!-- 忘记密码 -->
            <div class="forget">
              <span @click="forget">忘记密码</span>
            </div>
          </div>
          <div class="loginbtn" @click="login">登录</div>
        </div>
      </form>
    </div>
  </div>

  <!-- 忘记密码弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="忘记密码"
    width="500"
    :before-close="handleClose"
  >
    <el-form
      :model="form"
      ref="ruleFormRefPut"
      :rules="soilRules"
      class="updataForget"
    >
      <el-form-item label="电话：" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="form.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="新密码："
        :label-width="formLabelWidth"
        prop="password"
      >
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="确认密码："
        :label-width="formLabelWidth"
        prop="ispassword"
      >
        <el-input
          v-model="form.ispassword"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdate"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import Identify from "./Identify.vue";
import { ref, onMounted, reactive } from "vue";
import router from "@/router";
import { getLogin, putPassword } from "@/api/Login";
import { View, Hide } from "@element-plus/icons-vue";
const addPassFlag = ref(false); //图标显示标识

// 验证码
const identifyCode = ref("1234");
const identifyCodes = ref("1234567890");
// 改变验证码
function changeCode() {
  identifyCode.value = "";
  makeCode(identifyCodes.value, 4);
}
// 设置值
function makeCode(data, len) {
  for (let i = 0; i < len; i++) {
    identifyCode.value += data[randomNum(0, data.length - 1)];
  }
}
// 随机生成
function randomNum(min, max) {
  max = max + 1;
  return Math.floor(Math.random() * (max - min) + min);
}

// 账号密码
const username = ref("");
let password = ref("");
let remember = false;
let code = ref("");
const dialogVisible = ref(false);

// 规则
// 自定义校验规则 方法
let relusList = (rules, value, callback) => {
  //if 对两个输入框的value值进行必填校验
  if (!form.ispassword || !form.password) {
    return callback(new Error("确认密码不为空"));
    // 对第二个输入框进行正则校验
  } else if (form.ispassword !== form.password) {
    callback(new Error("密码必须一致"));
  } else {
    return callback();
  }
};
// 忘记密码表单
const form = reactive({
  phone: "",
  password: "",
  ispassword: "",
});

//密码表单校验输入的内容
const soilRules = reactive({
  phone: [
    {
      required: true,
      message: "电话号不为空",
      trigger: "blur",
    },
  ],
  password: [{ required: true, message: "新密码不为空", trigger: "blur" }],
  ispassword: [{ required: true, validator: relusList, trigger: "blur" }],
});

function handleUpdate() {
  if (form.password.trim() && form.ispassword.trim() && form.phone.trim()) {
    if (form.password.length < 6 || form.ispassword.length < 6) {
      ElNotification({
        title: "Error",
        message: "密码长度不能小于6",
        type: "error",
      });
    } else if (form.password.length > 16 || form.ispassword.length > 16) {
      ElNotification({
        title: "Error",
        message: "密码长度不能大于16",
        type: "error",
      });
    } else {
      if (form.password == form.ispassword) {
        putPassword(form).then(
          (res) => {
            if (res.code == 200) {
              ElNotification({
                title: "Success",
                message: "修改密码成功",
                type: "success",
              });
              form.phone = "";
              form.ispassword = "";
              form.password = "";
              dialogVisible.value = false;
            } else {
              ElNotification({
                title: "Error",
                message: "用户不存在",
                type: "error",
              });
            }
          },
          (err) => {
            ElNotification({
              title: "Error",
              message: "修改失败\r\n" + err.message,
              type: "error",
            });
          }
        );
      } else {
        ElNotification({
          title: "Error",
          message: "新密码与确认密码不一致",
          type: "error",
        });
      }
    }
  } else {
    ElNotification({
      title: "Error",
      message: "电话或密码不为空",
      type: "error",
    });
  }
}

// 忘记密码
function forget() {
  dialogVisible.value = true;
}

// 登录
function login() {
  if (!username.value.trim() || !password.value.trim()) {
    ElNotification({
      title: "Error",
      message: "账号或密码不能为空！",
      type: "error",
    });
  } else {
    if (code.value == identifyCode.value.trim()) {
      // 发送请求
      getLogin(username.value, password.value).then(
        (res) => {
          console.log(res.code);

          if (res.code == 200) {
            if (remember) {
              // 保存密码
              localStorage.setItem("password", password.value);
            }
            // 获取路由
            let routes = [];
            res.permissions.forEach((it) => {
              routes.push({
                label: it.label,
                route: it.route,
              });
            });
            sessionStorage.setItem("items", JSON.stringify(routes));
            sessionStorage.setItem("userinfo", JSON.stringify(res.uid));
            console.log(res.permissions);

            if (res.permissions.length !== 0) {
              sessionStorage.setItem("rname", res.permissions[0].rname);
              if (res.permissions[0].rname == "管理员") {
                router.push("/index/dashboard");
              } else {
                router.push("/index/device");
              }
            } else {
              router.push("/index/permissions");
            }
            // 设置token 跳转路由
            sessionStorage.setItem("token", res.token);
            ElNotification({
              title: "登录成功",
              message: "欢迎您！ " + res.permissions[0].rname,
              type: "success",
            });
            // 跳转首页
          } else {
            ElNotification({
              title: "Error",
              message: res.msg,
              type: "error",
            });
          }
        },
        (err) => {
          ElNotification({
            title: "Error",
            message: "用户名或密码错误，请重新输入！\r\n" + err.message,
            type: "error",
          });
        }
      );
    } else {
      ElNotification({
        title: "Error",
        message: "验证码错误",
        type: "error",
      });
    }
  }
}
// 记住密码
function setpassword() {
  // 如果被选中则存储密码
  if (document.getElementById("check").checked) {
    remember = true;
  } else {
    localStorage.setItem("password", "");
  }
}

// 钩子
onMounted(() => {
  sessionStorage.setItem("items", "[]");
  password.value = localStorage.getItem("password");
  if (password.value) {
    document.getElementById("check").checked = true;
  }
  changeCode();
});
</script>

<style lang="scss" scoped>
// 大盒子
.loginbox {
  width: 100vw;
  height: 100vh;
  display: flex;
  // 左盒子
  .left {
    height: 100vh;
    width: 65%;
    background: url("../../assets/bg.png") no-repeat;
    background-size: cover;
  }
  // 右盒子
  .right {
    margin: 0 auto;
    height: 100%;
    display: flex;
    align-items: center;
    width: 35%;
    // 登录表单
    .loginform {
      display: flex;
      flex-direction: column;
      margin: 30px;
      margin-left: 10%;
      width: 75%;
      height: 80%;
      .loginformHeader {
        margin-bottom: 20px;

        h2 {
          font-size: 50px;
          font-weight: bolder;
        }
        span {
          font-size: 30px;
          font-weight: bolder;
        }
      }
      .userlogin {
        margin-bottom: 20px;
        span {
          font-size: 22px;
          display: block;
          margin-top: 10px;
          margin-bottom: 5px;
        }
        // 账户盒子
        .userbox {
          div {
            width: 90% !important;
            height: 45px !important;
            :deep(div) {
              border-radius: 0 !important;
            }
          }
        }
      }
      // 密码盒子
      .passwordbox {
        div {
          width: 90% !important;
          height: 45px !important;
          :deep(div) {
            border-radius: 0 !important;
          }
        }
      }
    }
    // 验证码
    .codebox {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      div {
        width: 64% !important;
        height: 45px !important;
        :deep(div) {
          border-radius: 0 !important;
        }
      }
    }
    .otherbox {
      display: flex;
      width: 90%;
      justify-content: space-between;
      align-items: center;
      .forget {
        cursor: pointer;
      }
    }
    .loginbtn {
      margin-top: 20px;
      width: 109px !important;
      text-align: center;
      line-height: 45px;
      height: 45px;
      background-color: #3e5bb7;
      color: white;
      font-size: 18px;
      border: 0;
      border-radius: 5px;
      cursor: pointer;
      span {
        margin: 0;
      }
    }
  }
}

// 忘记密码弹窗
.updataForget {
  display: flex;
  flex-direction: column;
  span {
    font-size: 18px;
    margin-top: 10px;
    margin-bottom: 5px;
  }
  input {
    height: 40px;
    font-size: 24px;
  }
}
:deep(.el-form-item__label) {
  display: inline-block;
  width: 100px;
}
</style>
